import ast

import jwt
from django.http import JsonResponse
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
import json

# from car.data_analysis.data_analysis import get_keywords
from car.hive.hive_data import HiveUtils
from car.models import Car, CarsComment
from car.mysqql_connect.connect import MySQLUtils
from car.seriallzers import CarSerializer, CommentSerializer
from car.utls import transform_keywords
from user.models import User


# Create your views here.

@api_view(['POST'])
def carlist(request):
    manufacturers = list(Car.objects.values_list('manufacturers', flat=True).distinct())
    response_data = {
        'manufacturers': manufacturers,

    }
    return Response(response_data)

@api_view(['POST'])
def carlist_b_name(request):
    manufacturers = json.loads(request.body)
    page = int(request.data.get('page', 1))  # 默认为第一页
    page_size = int(request.data.get('page_size', 10))  # 默认每页显示 10 条数据
    queryset = Car.objects.filter(manufacturers=manufacturers['manufacturers'])
    categories = Car.objects.filter(manufacturers=manufacturers['manufacturers']).values_list('carname', flat=True).distinct()
    start_index = (page - 1) * page_size
    end_index = start_index + page_size
    paginated_data = queryset[start_index:end_index]
    serializer = CarSerializer(paginated_data, many=True)  # 序列化查询到的所有车辆信息
    response_data = {
        'categories': categories,
        'cars': serializer.data
    }
    return Response(response_data)

@api_view(['POST'])
def c_series_name(request):
    carname = json.loads(request.body)
    page = int(request.data.get('page', 1))  # 默认为第一页
    page_size = int(request.data.get('page_size', 10))  # 默认每页显示 10 条数据
    queryset = Car.objects.filter(carname=carname['carname'])
    start_index = (page - 1) * page_size
    end_index = start_index + page_size
    paginated_data = queryset[start_index:end_index]
    serializer = CarSerializer(paginated_data, many=True)  # 序列化查询到的所有车辆信息
    response_data = {
        'cars': serializer.data
    }
    return Response(response_data)


@api_view(['POST'])
def car_details(request):
    id = json.loads(request.body)
    page = int(request.data.get('page', 1))  # 默认为第一页
    page_size = int(request.data.get('page_size', 10))  # 默认每页显示 10 条数据
    queryset = Car.objects.filter(id=id)
    errormsg_values = queryset.values_list('errormsg', flat=True)
    queryset2 = CarsComment.objects.filter(car_id=id)
    start_index = (page - 1) * page_size
    end_index = start_index + page_size
    paginated_data = queryset2[start_index:end_index]
    queryset2 = queryset.values_list('key_word', flat=True)
    formatted_data = [{"name": key, "value": value} for item in queryset2 for key, value in item.items()]
    serializer = CarSerializer(queryset, many=True)  # 序列化查询到的所有车辆信息
    serializer2 = CommentSerializer(paginated_data, many=True)  # 序列化查询到的所有评论
    response_data = {
        'cars': serializer.data,
        'comments': serializer2.data,
        'errormsg':errormsg_values,
        'Radar_chart':queryset.values_list('Radar_chart', flat=True),
        'key_word':formatted_data
    }
    return Response(response_data)



# 获取指定汽车厂商的汽车信息
@api_view(['GET'])
def cars_by_make(request, make):
    try:
        cars = Car.objects.filter(make=make)
        serializer = CarSerializer(cars, many=True)
        return JsonResponse(serializer.data)
    except Car.DoesNotExist:
        return JsonResponse(status=status.HTTP_404_NOT_FOUND)

@api_view(['GET'])
def cars_by_model(request, model):
    try:
        cars = Car.objects.filter(make=model)
        serializer = CarSerializer(cars, many=True)
        return JsonResponse(serializer.data)
    except Car.DoesNotExist:
        return JsonResponse(status=status.HTTP_404_NOT_FOUND)

@api_view(['POST'])
def show_all_years_sales(request):
    try:
        start_date = request.data['start_date'][:4] + request.data['start_date'][5:7]
        end_date = request.data['end_date'][:4] + request.data['end_date'][5:7]
        mysql_utils = MySQLUtils(host='localhost', port=3306, user='root', password='root', database='carhouse')
        mysql_utils.connect()
        all_years_sales_data = mysql_utils.query_sales_by_date_range(int(start_date),int(end_date))
        sum_sales_by_car = mysql_utils.sum_sales_by_car(int(start_date),int(end_date))
        sum_automobilesales_by_year = mysql_utils.sum_automobilesales_by_year(int(start_date),int(end_date))
        print(sum_automobilesales_by_year)
        return JsonResponse({'all_years_sales_data': all_years_sales_data,'sum_sales_by_car':sum_sales_by_car,'sum_automobilesales_by_year':sum_automobilesales_by_year})
    except Exception as e:
        # 返回其他异常消息
        return JsonResponse({'message': str(e)})

@api_view(['POST'])
def get_automobile(request):
    try:
        getautomobile = list(Car.objects.values_list('manufacturers', flat=True).distinct())
        return JsonResponse({'manufacturers': getautomobile})
    except Exception as e:
    # 返回其他异常消息
        return JsonResponse({'message': str(e)})

@api_view(['POST'])
def get_carmsg(request):
    try:
        manufacturers = json.loads(request.body)
        car = Car.objects.filter(manufacturers=manufacturers['manufacturers'])
        car_msg = CarSerializer(car , many=True)
        return Response({'car_msg': car_msg.data})
    except Exception as e:
        # 返回其他异常消息
        return JsonResponse({'message': str(e)})

@api_view(['POST'])
def getsalesdata(request):
    try:
        carname = request.data['carname']['_rawValue']
        print(carname)
        start_date = request.data['start_date'][:4] + request.data['start_date'][5:7]
        end_date = request.data['end_date'][:4] + request.data['end_date'][5:7]
        mysql_utils = MySQLUtils(host='localhost', port=3306, user='root', password='root', database='carhouse')
        mysql_utils.connect()
        getcarnamedata = mysql_utils.getcarnamedata(start_date,end_date,carname)
        get_year_sales_data = mysql_utils.getallsmalldata(carname)
        hive_utils = HiveUtils(host='192.168.1.163', port=10000, database='default', auth_mechanism='PLAIN')
        sales_by_year = hive_utils.get_car_city_data(carname,start_date)
        sales_by_year_new = []
        for i in sales_by_year:
            # 去除外层引号并解析为字典
            parsed_data = ast.literal_eval(i[0])
            # 构造新的数据格式
            processed_data = [{"name": key.strip(), "value": int(value)} for key, value in parsed_data.items()]
            for item in processed_data:
                sales_by_year_new.append(item)
            break
        return JsonResponse({'get_year_sales_data': get_year_sales_data,'getcarnamedata':getcarnamedata,'sales_by_year':sales_by_year_new})
    except Exception as e:
        # 返回其他异常消息
        return JsonResponse({'message': str(e)})


@api_view(['POST'])
def addnewcomment(request):
    try:
        # 提取评论内容和令牌
        token = request.data.get('token')
        carid = request.data.get('carid')
        decoded_token = jwt.decode(token, options={"verify_signature": False})
        user_id = decoded_token.get('user_id')
        comments = CarsComment.objects.filter(user_id=user_id, car_id=carid)
        if comments.exists():
            return Response({'message': '你已经发表过评论，请勿重复发表'})
        else:
            # 构建雷达图数据字典
            radar_data = {
                'space': request.data.get('space', None),
                'configuration': request.data.get('configuration', None),
                'drivingExperience': request.data.get('drivingExperience', None),
                'appearance': request.data.get('appearance', None),
                'interior': request.data.get('interior', None),
                'costPerformance': request.data.get('costPerformance', None),
            }
            # 查询Car实例
            car = Car.objects.get(pk=carid)
            # 处理Radar_chart
            if car.Radar_chart:
                # 已有雷达图数据，合并并计算平均值
                for key in radar_data.keys():
                    # 确保新老数据都存在且为数值类型，否则跳过
                    if radar_data[key] is not None and car.Radar_chart.get(key) is not None:
                        avg_value = (radar_data[key] + car.Radar_chart[key]) / 2
                        car.Radar_chart[key] = round(avg_value, 2)
                    elif radar_data[key] is not None:  # 如果旧数据不存在，直接使用新数据
                        car.Radar_chart[key] = round(radar_data[key], 2)
            else:
                # 无雷达图数据，直接使用新数据
                car.Radar_chart = radar_data
            # 保存Car实例
            car.save(update_fields=['Radar_chart'])
            title = request.data.get('title')
            mileage = request.data.get('mileage', None)
            fuelConsumption = request.data.get('fuelConsumption', None)
            price = request.data.get('price', None)
            purchaseTime = request.data.get('purchaseTime', None)
            purchaseLocation = request.data.get('purchaseLocation', None)
            advantages = request.data.get('advantages', None)
            disadvantages = request.data.get('disadvantages', None)
            car = CarsComment.objects.create(
                car_id=carid,
                title=title,
                mileage=mileage,
                fuel=fuelConsumption,
                price=price,
                buy_time=purchaseTime,
                address=purchaseLocation,
                satisfied=advantages,
                dissatisfied=disadvantages,
                user_id=user_id
            )

            return Response({'message': '成功发表评论'})
    except Exception as e:
        return Response({'message': e})



@api_view(['POST'])
def likeuser(request):
    try:
        # 提取评论内容和令牌
        token = request.data.get('token')
        likeuser_id = request.data.get('likeuser_id')
        decoded_token = jwt.decode(token, options={"verify_signature": False})
        user_id = decoded_token.get('user_id')
        # 使用 get 方法获取单个用户对象
        user = User.objects.get(id=user_id)
        # 添加关注
        like_user = User.objects.get(id=likeuser_id)
        user.concern.add(like_user)
        return Response({'message': '关注成功'})
    except Exception as e:
        return Response({'message': e})

